# @Time    : 2021/1/19 14:23
# @Author  : LDY
# @Email   : 274884591@qq.com
# @File    : orderTreasure.py
# @desc    : 订货宝业务代码
# @Software: PyCharm
import time
import requests
import urllib3
import jsonpath


class OrderTreasure:
    def __init__(self):
        self.session = requests.Session()
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        # cookie从网页中复制粘贴
        self.cookie = 'pagesize_cookie=30; session_id=d7eae14956ce6a98ea1a4b369e13d757; client_session_id=eea6496ae8a330b7a9ee4149e38f0050; _TOKEN=e217a61dcba1c3817cab635b696e02bc98e642009aeef6c983e85b8c21264705%2BImUQGfEej5%2F55QhP%2FadOfhTpYmIdP5taZ6KFWApUN2qI71goPvRcgPJY%2FuSd%2BFpmeQW%2FkFZGVBKhaLNOYkHi242spYXKLCjCSv7Di1CQ5UoSo2o8df8eL2a7a0KypMrn620K9KFE7%2FAj30IO8bRHQ2z1Iyiin2zs4TxQAqvoWj4%3D'
        self.header = {'Cookie': self.cookie}

    # 查询商品信息
    def query_goods(self, kw='', category_id='', brand_id='', stock_id='', has_picture=''):
        """
        参数说明
        :param kw: 搜索框输入关键字
        :param category_id: 商品分类
        :param brand_id: 商品品牌
        :param stock_id: 商品仓库
        :param has_picture: 商品是否有图
        :return:
        """
        url = 'https://admin.dhb168.com/RestfulApi/goods'
        params = {'group_by': 'goods',
                  'kw': kw,
                  'category_id': category_id,
                  'brand_id': brand_id,
                  'stock_id': stock_id,
                  'has_picture': has_picture}
        response = self.session.get(url, params=params, headers=self.header)
        return response.json()

    # 新增商品
    def add_goods(self, goods_name, category_id, brand_id, min_order, stock_id, goods_num, whole_price, base_units):
        """
        参数说明
        :param goods_name: 商品名称
        :param category_id: 商品分类
        :param brand_id: 商品品牌
        :param min_order: 起订量
        :param stock_id: 仓库名
        :param goods_num: 商品编号
        :param whole_price: 订货价
        :param base_units: 商品基本单位
        :return:
        """
        url = 'https://admin.dhb168.com/Manager/Goods/updateGoods'
        data = {'goods_name': goods_name,
                'category_id': category_id,
                'brand_id': brand_id,
                'min_order': min_order,
                'stock_id': stock_id,
                'goods_num': goods_num,
                'order_units': 'base_units',
                'translation': 1,
                'putaway': 'T',
                'whole_price': whole_price,
                'base_units': base_units
                }
        response = self.session.post(url, data=data, headers=self.header)
        # 如果新增成功则删除，保持数据整洁
        if response.json().get('status') == 'success':
            result = self.query_goods(goods_name, category_id, brand_id, stock_id)
            # 获取刚新增的商品的ID
            goods_id_list = jsonpath.jsonpath(result, '$.data.list[*].goods_id')
            for goods_id in goods_id_list:
                # 删除此商品
                time.sleep(2)
                self.delete_goods(goods_id)
        return response.json()

    # 删除单个商品
    def delete_goods(self, goods_id):
        url = f'https://admin.dhb168.com/RestfulApi/goods/{goods_id}'
        data = {'_method': 'delete'}
        response = self.session.post(url, data=data, headers=self.header)
        return response.json()

    # 设置库存预警
    def inventory_warning(self, data_str, goods):
        """
        参数说明
        :param data_str: {"upper":6,"floor":2,"safety":4}上限，下限，安全库存
        :param goods: 商品id
        :return:
        """
        url = 'https://admin.dhb168.com/RestfulApi/goods/batch/goodsinventory'
        data = {'_method': 'put',
                'data': data_str,
                'goods': goods}
        response = self.session.post(url, data=data, headers=self.header)
        return response.json()

    # 设置商品品牌
    def modify_brand(self, data_str, goods):
        """
        参数说明
        :param data_str: 商品品牌ID
        :param goods: 商品ID
        :return:
        """
        url = 'https://admin.dhb168.com/RestfulApi/goods/batch/goods_brand'
        data = {'_method': 'put',
                'data': data_str,
                'goods': goods}
        response = self.session.post(url, data=data, headers=self.header)
        return response.json()

    # 设置商品分类
    def modify_category(self, data_str, goods):
        """
        参数说明
        :param data_str: 商品分类ID
        :param goods: 商品ID
        :return:
        """
        url = 'https://admin.dhb168.com/RestfulApi/goods/batch/goodscategory'
        data = {'_method': 'put',
                'data': data_str,
                'goods': goods}
        response = self.session.post(url, data=data, headers=self.header)
        return response.json()

    # 设置商品标识
    def modify_logo(self, data_str, goods):
        """
        参数说明
        :param data_str: '1,2,3,4,94'标识ID
        :param goods:商品ID
        :return:
        """
        url = 'https://admin.dhb168.com/RestfulApi/goods/batch/goodstype'
        data = {'_method': 'put',
                'data': data_str,
                'goods': goods}
        response = self.session.post(url, data=data, headers=self.header)
        return response.json()

    # 加载图片到静态文件服务器
    def save_static_image(self, image_name, image_path, image_type):
        """
        参数说明
        :param image_name: 图片名
        :param image_path: 图片路径
        :param image_type: 图片类型 'image/jpg'
        :return:
        """
        url = 'https://admin.dhb168.com/?module=Quote&controller=Upload&action=uploadPicture&config=goods_thumb&type=other'
        data = {'name': image_name}
        with open(image_path, 'rb') as f:
            files = {'file': (image_name, f, image_type)}
            response = self.session.post(url, data=data, headers=self.header, files=files)
            result = response.json()
            # 获取图片的图片名，路径及大小
            file_name = result.get('name')
            file_path = result.get('path')
            file_size = jsonpath.jsonpath(result, '$.imageList[0].size')
            if type(file_size) == list:
                file_size = file_size[0]
            return file_name, file_path, file_size

    # 上传商品图片
    def upload_image(self, goods_id, image_name, image_path, image_type):
        """
        参数说明
        :param goods_id: 商品ID
        :param image_name: 图片名
        :param image_path: 图片路径
        :param image_type: 图片类型
        :return:
        """
        # 加载图片到静态文件
        file_tuple = self.save_static_image(image_name, image_path, image_type)
        url = 'https://admin.dhb168.com/index.php?module=Manager&controller=Resource&action=multiSave'
        data = {'type': 'goods',
                'goods_id': goods_id,
                'old_name[]': image_name,
                'file_name[]': file_tuple[0],
                'file_path[]': file_tuple[1],
                'file_size[]': file_tuple[2],
                'order_num': 500}
        response = self.session.post(url, data=data, headers=self.header)
        return response.json()

    # 商品上下架
    def set_shelf(self, putaway, goods_id):
        """
        参数说明
        :param putaway: 上下架标志 T-上架 F-下架
        :param goods_id: 商品ID
        :return:
        """
        url = 'https://admin.dhb168.com/?module=Manager&controller=GoodsParticulars&action=updateGoodsInfo'
        data = {'putaway': putaway,
                'goods_id': goods_id}
        response = self.session.post(url, data=data, headers=self.header)
        return response.json()

    # 商品批量上下架
    def set_batch_shelf(self, putaway, goods_id):
        """
        参数说明
        :param putaway: 上下架标志 T-上架 F-下架
        :param goods_id: 商品ID
        :return:
        """
        url = 'https://admin.dhb168.com/?module=Manager&controller=GoodsParticulars&action=batchUpdate'
        data = {'putaway': putaway,
                'goods_id': goods_id}
        response = self.session.post(url, data=data, headers=self.header)
        return response.json()

    # 设置商品阶梯价格
    def set_number_price(self, price_dict, price_id, enable_price):
        """
        参数说明
        :param price_dict: 阶梯价格字典键为订货量，值为订货价
        :param price_id: 价格ID对应一个商品
        :param enable_price: 是否开启阶梯价格开关 'T'代表开启 'F'代表关闭
        :return:
        """
        url = 'https://admin.dhb168.com//Manager/GoodsPrice/setNumberPrice'
        data = {'price': price_dict,
                'price_id': price_id,
                'enable_price': enable_price}
        response = self.session.post(url, data=data, headers=self.header)
        return response.json()

    # 王清玉
    # 客户-客户积分-明细
    def client_Integration_detail(self, client_integral_id):
        """
        :param client_integral_id: 客户ID
        :return:
        """
        url = 'https://admin.dhb168.com/Integral_Client/getClientIntegralDetail?'
        data = f'client_integral_id={client_integral_id}'
        headers = {'content-type': 'application/x-www-form-urlencoded', 'cookie': self.cookie}
        response = self.session.get(url, params=data, headers=headers)
        return response.json()

    # 批量设置供应商
    def modify_supplier(self, method, data, goods):
        """
        :param method:方法
        :param data:数据
        :param goods:商品类型
        :return:
        """
        url = 'https://admin.dhb168.com/RestfulApi/goods/batch/goods_supplier'
        data = {'_method': method,
                'data': data,
                'goods': goods}
        response = self.session.post(url, data=data, headers=self.header)
        return response.json()

    # 库存-供应商-查询
    def stock_SQE_search(self, kw):
        """
        :param kw: 供货商名字
        :return: 返回的是html页面
        """
        url = 'https://admin.dhb168.com/?'
        data = {'module': 'Manager',
                'controller': 'Supplier',
                'action': 'index',
                '_search_': '1',
                'kw': kw}
        response = self.session.get(url=url, params=data, headers=self.header)
        return response.text

    # 库存-供应商-新增供应商
    def stock_SQE_addSqe(self, client_name, client_num, city_id, address, remark, contact, mobile, phone, email,
                         account_name, bank, bank_account, invoice_title, taxpayer_number, client_id):
        """
        :param client_name: 供应商名字
        :param client_num: 供应商编号
        :param city_id: 联系地址
        :param address: 详细地址
        :param remark: 备注
        :param contact: 联系人姓名
        :param mobile: 手机电话
        :param phone: 座机
        :param email: 邮箱
        :param account_name: 开户名称
        :param bank: 开户银行
        :param bank_account: 银行账号
        :param invoice_title: 开票抬头
        :param taxpayer_number: 纳税人识别号
        :param client_id: 供应商ID
        :return:
        """
        url = 'https://admin.dhb168.com/index.php?module=Manager&controller=Supplier&action=saveSupplier'
        data = f'client_name={client_name}&client_num={client_num}&city_id={city_id}&address={address}&remark={remark}&contact={contact}&mobile={mobile}&phone={phone}&email={email}&account_name={account_name}&bank={bank}&bank_account={bank_account}&invoice_title={invoice_title}&taxpayer_number={taxpayer_number}&client_id={client_id}'
        headers = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Cookie': self.cookie}
        response = self.session.post(url, data=data.encode('utf-8'), headers=headers)
        return response.json()

    # 库存-采购单-查询
    def stock_order_search(self, kw):
        """
        :param kw: 根据采购单的名称查询
        :return:
        """
        url = 'https://admin.dhb168.com/Api/v1/purchases?'
        data = f'page=0&pageSize=10&delivery_date=2020-12-28&kw={kw}'
        headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': self.cookie}
        response = self.session.get(url, params=data, headers=headers)
        return response.json()

    # 库存-采购退货单-查询
    def stock_returnGoodsOrders_search(self, status):
        """
        :param status: 根据采购退货单的状态查询
        :return:
        """
        url = 'https://admin.dhb168.com/Api/v1/returns?'
        data = f'page=0&pageSize=10&return_send_date=2020-12-28+00:00&status={status}'
        headers = {'content-type': 'application/x-www-form-urlencoded', 'Cookie': self.cookie}
        response = self.session.get(url, params=data, headers=headers)
        return response.json()

    # 库存-供应商管理-修改
    def stock_SQE_update(self, client_name, client_num, city_id, address, remark, contact, mobile, phone, email,
                         account_name, bank, bank_account, invoice_title, taxpayer_number):
        """
        :param client_name: 供应商名字
        :param client_num: 供应商编号
        :param city_id: 联系地址
        :param address: 详细地址
        :param remark: 备注
        :param contact: 联系人姓名
        :param mobile: 手机电话
        :param phone: 座机
        :param email: 邮箱
        :param account_name: 开户名称
        :param bank: 开户银行
        :param bank_account: 银行账号
        :param invoice_title: 开票抬头
        :param taxpayer_number: 纳税人识别号
        :return:
        """
        url = 'https://admin.dhb168.com/index.php?module=Manager&controller=Supplier&action=saveSupplier'
        data = f'client_name={client_name}&client_num={client_num}&city_id={city_id}&address={address}&remark={remark}&contact={contact}&mobile={mobile}&phone={phone}&email={email}&account_name={account_name}&bank={bank}&bank_account={bank_account}&invoice_title={invoice_title}&taxpayer_number={taxpayer_number}&client_id=7840711'
        headers = {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'cookie': self.cookie}
        response = self.session.post(url, data=data.encode('utf-8'), headers=headers)
        return response.json()

    # 库存-常用物流公司-启用或停用物流
    def stock_logisticsCompany(self, id, apply):
        """
        :param id: 物流公司编号
        :param apply: 物流公司状态
        :return:
        """
        url = 'https://admin.dhb168.com/index.php?module=Manager&controller=Base&action=setStatus'
        data = f'id={id}&apply={apply}'
        headers = {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'cookie': self.cookie}
        response = self.session.post(url, data=data, headers=headers)
        return response.json()

    # 库存-采购订单-页面显示数量
    def stock_order_dataSize(self, pageSize, kw):
        """
        :param pageSize: 页面显示数量
        :param kw: 采购单名称(模糊查询)
        :return:
        """
        url = 'https://admin.dhb168.com/Api/v1/purchases?'
        data = f'page=0&pageSize={pageSize}&delivery_date=2020-12-28&kw={kw}'
        headers = {'content-type': 'application/json; charset=utf-8', 'cookie': self.cookie}
        response = self.session.get(url, data=data, headers=headers)
        return response.json()

    # 余托弟
    # 订单货单——查询
    def indent_Query(self, start_time, kw=None, status=None, start_time_end=None, page=1, pageSize=10, pay_status=None):
        '''
        :param start_time: 开始时间
        :param status:     订单状态
        :param start_time_end: 截止时间
        :param page:        当前所在页
        :param pageSize:     一页最大显示
        :param kw:          搜索框
        :param pay_status: 收款状态
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/order?'
        par = {'page': page,
               'pageSize': pageSize,
               'start_time': start_time,
               'kw': kw,
               'status': status,
               'pay_status': pay_status,
               'start_time_end': start_time_end
               }
        response = self.session.get(url, params=par, headers=self.header)
        res = response.json()
        return res

    # 订货单——商品统计
    def GoodSstatis_Orderinfo(self, start_time, merge=None, page=1, pageSize=10):
        '''
        :param page:  当前页面
        :param pageSize:
        :param merge:   查询方式：全部、按客户、按商品
        :param start_time:  开始时间
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/order/goods_info/order_info'
        par = {'page': page,
               'pageSize': pageSize,
               'merge': merge,
               'start_time': start_time}
        response = self.session.get(url, params=par, headers=self.header)
        res = response.json()
        return res

    # 发货单——查询
    def fahuo_Query(self, start_time, ships_date, client_id=None, status=None, kw=None, page=1, pageSize=10,
                    endtime=None, ships_data_end=None, ):
        '''
        :param start_time: 开始出库时间
        :param status:   发货状态
        :param client_id:  选择客户
        :param kw:     输入框
        :param page:  当前所在页
        :param pageSize:当前页面最大显示页
        :param endtime: 出库结束时间
        :param ships_date: 开始运输日期
        :param ships_data_end:  结束运输时间
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/order/delivery'
        par = {'kw': kw,
               'status': status,
               'client_id': client_id,
               'page': page,
               'pageSize': pageSize,
               'start_time': start_time,
               'start_time_end': endtime,
               'ships_date': ships_date,
               'ships_date_end': ships_data_end}
        response = self.session.get(url, params=par, headers=self.header)
        res = response.json()
        return res

    # 订货单———新增———客户输入框
    def order_Addsearch(self, CusName, salesMan=None):
        '''
        :param CusName:  客户名称
        :param salesMan:  业务员
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/AddOrder/AddOrder/staffs'
        param = {'client_id': CusName,
                 'orders_id': salesMan}
        response = self.session.get(url, params=param, headers=self.header)
        res = response.json()
        return res

    # 资金———订单应收款——查询方式（按订单/按客户）
    def fund_Pay_Query(self, startTime, kw=None, query_mode=0, page=1, pageSize=10, endTime=None):
        '''
        :param startTime: 开始时间
        :param kw:  订单号输入框
        :param query_mode: 查询方式，默认为0:按订单，1:按客户
        :param page:
        :param pageSize:
        :param endTime:
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/payments'
        param = {'is_group': query_mode,
                 'kw': kw,
                 'page': page,
                 'pageSize': pageSize,
                 'start_time': startTime,
                 'start_time_end': endTime}
        response = self.session.get(url, params=param, headers=self.header)
        res = response.json()
        return res

    # 订单应收款————收款
    def fund_Payee(self, orderNum):
        '''
        :param orderNum: 订单号
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/pay-info/' + orderNum
        param = {'id': orderNum}
        response = self.session.get(url, params=param, headers=self.header)
        res = response.json()
        return res

    # 收款确认
    def pay_Queren(self, pay_type, price, bank_id, receipts_date, orders_id):
        '''
        :param pay_type: 收款方式
        :param price:  收款金额
        :param bank_id:收款账号
        :param receipts_date:收款日期
        :param orders_id:
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/receipts'
        data = {'pay_type': pay_type,
                'price': price,
                'bank_id': bank_id,
                'receipts_date': receipts_date,
                'orders_id': orders_id
                }
        response = self.session.post(url, data=data, headers=self.header)
        text = response.text
        return text

    # 收款确认————查看
    def payee_AffirmCheck(self, oddNum):
        '''
        :param oddNum: 单号
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/receipts/' + oddNum
        param = {'receipts_id': oddNum}
        response = self.session.get(url, params=param, headers=self.header)
        res = response.json()
        return res

    # 预付款管理——查询
    def payment_guanli_Query(self, kw=None, sort=None, page=1, pageSize=10):
        '''
        :param kw:  输入框
        :param sort: 排序 （预付款从小到大/预付款从大到小/默认排序为None）
        :param page:
        :param pageSize:
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/purchase-deposits'
        param = {'page': page,
                 'pageSize': pageSize,
                 'sort_order': sort,
                 'kw': kw}
        response = self.session.get(url, params=param, headers=self.header)
        res = response.json()
        return res

    # 收款确认-确认
    def queRen(self, Cusid):
        '''
       :param id:
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/receipts/update'
        data = {'id': Cusid}
        response = self.session.post(url, data=data, headers=self.header)
        text = response.text
        return text

    def zijinliushui(self, kw=None, bank_id=None, page=1, pageSize=10, hide_canceled=0):
        '''
        :param kw: 搜索框
        :param bank_id: 开户银行
        :param page:
        :param pageSize:
        :param hide_canceled:
        :return:
        '''
        url = 'https://admin.dhb168.com/RestfulApi/purchase-receipts'
        param = {'page': page,
                 'pageSize': pageSize,
                 'hide_canceled': hide_canceled,
                 'kw': kw,
                 'bank_id': bank_id
                 }
        response = self.session.get(url, params=param, headers=self.header)
        res = response.json()
        return res


if __name__ == '__main__':
    o = OrderTreasure()
    # o.modify_logo()
    # o.stock_SQE_search()
    # o.stock_SQE_addSqe()
    # o.stock_order_search()
    # o.stock_returnGoodsOrders_search()
    # o.stock_SQE_update()
    # o.stock_logisticsCompany()
    # o.client_Integration_detail()
    # o.stock_order_dataSize()
    order = OrderTreasure()
    # print(order.modify_logo('', '61401248'))
    # print(order.modify_brand('中文', '61401248'))
    # print(order.modify_category('', '61342052'))
    # print(order.inventory_warning({"upper":-1,"floor":'',"safety":'中文'}, 61401248))
    # print(order.query_goods('', '', '', '', ''))
    # print(order.add_goods('测试商品9999', '31182', '20276', '2.00', '10603', '100171', '30.00', '升'))
    # print(order.delete_goods(61404798))
    # image_path1 = r'E:\培训学习\综合实践\GitStore\oredertreasure\TestData\API\Ordertreasure\Pictures\a.png'
    # print(order.save_static_image('aB.png', image_path1, 'image/jpeg'))
    # print(order.upload_image(61401248, 'aV.png', image_path1, 'image/plng'))
    # print(order.set_shelf('F', 61401248))
    # print(order.set_batch_shelf('F', '61342052,61401239'))
    # print(order.set_number_price('{"0":"-1","10":"40.00","20":"30.00"}', 200227951, 'T'))
